<?php

namespace Track\Controller;

use Plume\Core\Controller;
use Plume\Core\Service;
use Plume\Core\Dao;

class IndexController extends Controller{

	private $listService = null;

    public function __construct($app) {
        parent::__construct($app, new Service($app, new Dao($app, 'track_user')));
        $this->listService = new Service($app, new Dao($app, 'track_list'));
    }

    private function checklogin(){
        $login = $this->provider('session')->getSessionValue('status');
        if(empty($login) || $login === false){
            header("location:/track/index/index");
        }
    }

    public function indexAction(){
        $login = $this->provider('session')->getSessionValue('status');
        if(!empty($login) && $login === true){
            header("location:/track/index/list");
        }
        return $this->result(array())->response();
    }

    public function logoutAction(){
        $this->api();
        $this->provider('session')->unsetSession('status');
        header("location:/");
    }

    public function loginAction(){
        $this->api();
        if (!$this->api()->isPost()) {
            return $this->msg(5008, '非法请求')->response();
        }
        $name = $this->getParamValue('name');
        $passwd = $this->getParamValue('passwd');
        if($name === 'infobird' && $passwd === 'nhds12345'){
            $this->provider('session')->setSessionValue('status', true);
            $this->provider('session')->setSessionValue('loginname', $name);
        }else{
            return $this->msg(500, '验证失败')->response();
        }
        return $this->msg(200, '验证通过')->response();
    }

	public function listAction() {
        $this->checklogin();
        $date = $this->getParamValue('date');
        $name = $this->getParamValue('name');
        $qq = $this->getParamValue('qq');
        $tel = $this->getParamValue('tel');
        $comname = $this->getParamValue('comname');
        $note = $this->getParamValue('note');
        $where = array();
        $sql = 'select * from track_user where 1=1';
        $sqlCon = '';
        $sqlWhere = array();
        if(!empty($date)){
            $where['date'] = $date;
            $sqlCon .= ' and date = ?';
            $sqlWhere[] = $date;
        }
        if(!empty($name)){
            $where['name'] = $name;
            $sqlCon .= " and name like ?";
            $sqlWhere[] = '%'.$name.'%';
        }
        if(!empty($qq)){
            $where['qq'] = $qq;
            $sqlCon .= ' and qq like ?';
            $sqlWhere[] = '%'.$qq.'%';
        }
        if(!empty($tel)){
            $where['tel'] = $tel;
            $sqlCon .= ' and tel like ?';
            $sqlWhere[] = '%'.$tel.'%';
        }
        if(!empty($comname)){
            $where['comname'] = $comname;
            $sqlCon .= ' and comname like ?';
            $sqlWhere[] = '%'.$comname.'%';
        }
        if(!empty($note)){
            $where['note'] = $note;
            $sqlCon .= ' and note like ?';
            $sqlWhere[] = '%'.$note.'%';
        }
        //分页信息处理
        $pageInfo = array();
        //分页参数配置
        $pageInfo['pageLimit'] = 6;
        //总记录数
        $totalSql = 'select count(id) as total from track_user where 1=1';
        $totalSql .= $sqlCon;
        $pageInfo['total'] = $this->service->queryBySql($totalSql, $sqlWhere)[0]['total'];
        if($pageInfo['total'] === 0){
            return $this->result(array('users' => array(), 'where' => $where, 'pageInfo' => $pageInfo))->response();
        }
        //总页数
        $pageInfo['totalPage'] = ceil($pageInfo['total']/$pageInfo['pageLimit']);
        //当前页数
        $pageInfo['page'] = $this->getParamValue('page');
        $pageInfo['page'] = (!is_numeric($pageInfo['page']) || $pageInfo['page'] <= 0) ? 1 : $pageInfo['page'];
        if($pageInfo['page'] >= $pageInfo['totalPage']){
            $pageInfo['page'] = $pageInfo['totalPage'];
        }
        //前后箭头判断
        $pageInfo['prev'] = (($pageInfo['page']-1)>0) ? '' : 'disabled';
        $pageInfo['prevNum'] = (($pageInfo['page']-1)>0) ? ($pageInfo['page']-1) : 1;
        $pageInfo['next'] = (($pageInfo['page']+1)<=$pageInfo['totalPage']) ? '' : 'disabled';
        $pageInfo['nextNum'] = (($pageInfo['page']+1)<=$pageInfo['totalPage']) ? ($pageInfo['page']+1) : $pageInfo['totalPage'];
        //获取记录
        $startLimit = $pageInfo['pageLimit']*($pageInfo['page']-1);
        $sql .= $sqlCon;
        $sql .= " limit {$startLimit} , {$pageInfo['pageLimit']}";

        $usersInfo = $this->service->queryBySql($sql, $sqlWhere);
        return $this->result(array('users' => $usersInfo, 'where' => $where, 'pageInfo' => $pageInfo))->response();
	}

    public function editAction() {
        $this->checklogin();
        $id = $this->getParamValue('id');
        if (!empty($id)) {
            $userInfoArr = $this->service->fetchById($id);
            if (!empty($userInfoArr)) {
                return $this->result(array('user_info'=>$userInfoArr[0]))->response();
            }
            //记录日志，系统处理异常
            $this->log('该条记录不存在', array('data'=>$id));
            //返回正常数据
            return $this->result(array('user_error' => '用户'.$id.'不存在'))->response();
        }
        return $this->result(array())->response();
        
    }

    public function trackAction(){
        $this->checklogin();
    	$id = $this->getParamValue('id');
        if (!empty($id)) {
            $userInfoArr = $this->service->fetchById($id);
            if (!empty($userInfoArr)) {
                $where = array('track_userid' => $id);
                $trackList = $this->listService->fetch($where);
                return $this->result(array('user_info'=>$userInfoArr[0], 'track_list' => $trackList))->response();
            }
            //记录日志，系统处理异常
            $this->log('该条记录不存在', array('data'=>$id));
            //返回正常数据
            return $this->result(array('user_error' => '用户'.$id.'不存在'))->response();
        }
        return $this->result(array())->response();

    }

    public function deleteAction(){
        $this->api();
        // //API请求，判断请求类型
        if (!$this->api()->isPost()) {
            //返回JSON消息
            return $this->msg(5008, '非法请求')->response();
        }
        $id = $this->getParamValue('id');
        if (empty($id)) {
            return $this->msg(5009, '用户ID不存在')->response();  
        }
        $result = $this->service->deleteById($id);
        if ($result) {
            $this->msg(5000, "删除成功");
        }else{
            $this->msg(5001, "删除失败");
        }
        //分解链式操作，统一返回
        return $this->response();
    }

    public function tracksaveAction() {
        if (!$this->api()->isPost()) {
            return $this->msg(5008, '非法请求')->response();
        }

        $id = $this->getParamValue('id');
        $userid = $this->getParamValue('userid');
        $trackdate = $this->getParamValue('date');
        $trackname = $this->getParamValue('name');
        $trackdetail = $this->getParamValue('detail');
        //添加
        if (empty($id)) {
            $insertData = array(
                'track_userid' => $userid,
                'track_date' => $trackdate,
                'track_name' => $trackname,
                'track_detail' => $trackdetail
            );
            $insertRet = $this->listService->insert($insertData);    
            if (!$insertRet) {
                return $this->msg(5000, $this->provider('dataBase')->connect()->getLastError())->response();
            }
            return $this->msg(200, "新增成功")->response();
        } else {
            //更新
            $updateRet = $this->service->update(
            array(
                'date' => $date,
                'from' => $from,
                'fromkey' => $fromkey,
                'name' => $name,
                'area' => $area,
                'qq' => $qq,
                'tel' => $tel,
                'mail' => $mail,
                'nhtype' => $nhtype,
                'comname' => $comname,
                'nhscope' => $nhscope,
                'step' => $step,
                'note' => $note
            ), array('id' => $id));
            if (!$updateRet) {
                return $this->msg(5000, "更新失败")->response();
            }
            return $this->msg(0, "更新成功")->response();
        }
    }

    public function saveAction() {
        $this->api();
        // if (!$this->api()->isPost()) {
        //     return $this->msg(5008, '非法请求')->response();
        // }
        $id = $this->getParamValue('id');
        $date = $this->getParamValue('date');
        $date = empty($date)?date('Y-m-d').' 00:00:00':$date;
        $from = $this->getParamValue('from');
        $fromkey = $this->getParamValue('fromkey');
        $name = $this->getParamValue('name');
        $area = $this->getParamValue('area');
        $qq = $this->getParamValue('qq');
        $tel = $this->getParamValue('tel');
        $mail = $this->getParamValue('mail');
        $nhtype = $this->getParamValue('nhtype');
        $comname = $this->getParamValue('comname');
        $nhscope = $this->getParamValue('nhscope');
        $step = $this->getParamValue('step');
        $note = $this->getParamValue('note');
        //添加
        if (empty($id)) {
            $insertData = array(
                'date' => $date,
                'from' => $from,
                'fromkey' => $fromkey,
                'name' => $name,
                'area' => $area,
                'qq' => $qq,
                'tel' => $tel,
                'mail' => $mail,
                'nhtype' => $nhtype,
                'comname' => $comname,
                'nhscope' => $nhscope,
                'step' => $step,
                'note' => $note
            );
            $insertRet = $this->service->insert($insertData);    
            if (!$insertRet) {
                // return $this->msg(5000, "新增失败")->response();
                return $this->msg(5000, $this->provider('dataBase')->connect()->getLastError())->response();
            }
            return $this->msg(0, "新增成功")->response();
        } else {
            //更新
            $updateRet = $this->service->update(
            array(
            	'date' => $date,
            	'from' => $from,
            	'fromkey' => $fromkey,
            	'name' => $name,
            	'area' => $area,
            	'qq' => $qq,
            	'tel' => $tel,
            	'mail' => $mail,
            	'nhtype' => $nhtype,
            	'comname' => $comname,
            	'nhscope' => $nhscope,
            	'step' => $step,
				'note' => $note
			), array('id' => $id));
            if (!$updateRet) {
                return $this->msg(5000, "更新失败")->response();
            }
            return $this->msg(0, "更新成功")->response();
        }
    }
}